package main.java.com.itlin.datastructure.deque;

import java.util.Iterator;

public class LinkedListDeque<E> implements Deque<E>,Iterable<E>{

    static class Node<E>{
        Node<E> prev;
        E value;
        Node<E> next;

        public Node(Node<E> prev, E value, Node<E> next){
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    int capacity;
    int size;
    Node<E> sentinal = new Node<>(null, null, null);

    public LinkedListDeque(int capacity){
        this.capacity = capacity;
        sentinal.next = sentinal;
        sentinal.prev = sentinal;
    }
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            Node<E> p = sentinal.next;
            @Override
            public boolean hasNext() {
                return p != sentinal;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    //a added b
    @Override
    public boolean offerFirst(E e) {
        if (isFull()) return false;
        Node<E> a = sentinal;
        Node<E> b = sentinal.next;
        Node<E> added = new Node<>(a,e,b);
        a.next = added;
        b.prev = added;
        size++;
        return true;
    }

    //a added b
    @Override
    public boolean offerLast(E e) {
        if (isFull()) return false;
        Node<E> b = sentinal;
        Node<E> a = sentinal.prev;
        Node<E> added = new Node<E>(a,e,b);
        a.next = added;
        b.prev = added;
        size++;
        return true;
    }

    @Override
    public E pollFirst() {
        if(isEmpty()) return null;
        Node<E> a = sentinal;
        Node<E> b = sentinal.next.next;
        Node<E> removed = sentinal.next;
        a.next = b;
        b.prev = a;
        size--;
        return removed.value;
    }

    @Override
    public E pollLast() {
        if (isEmpty()) return null;
        Node<E> b = sentinal;
        Node<E> removed = b.prev;
        Node<E> a = removed.prev;
        a.next = b;
        b.prev = a;
        size--;
        return removed.value;
    }

    @Override
    public E peekFirst() {
        if (isEmpty()) return null;
        return sentinal.next.value;
    }

    @Override
    public E peekLast() {
        if (isEmpty()) return null;
        return sentinal.prev.value;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }
}
